/*
   Copyright 2020 The Compose Specification Authors.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package types

import (
	"fmt"
	"github.com/docker/go-units"
)

// UnitBytes is the bytes type
type UnitBytes int64

// MarshalYAML makes UnitBytes implement yaml.Marshaller
func (u UnitBytes) MarshalYAML() (interface{}, error) {
	return fmt.Sprintf("%d", u), nil
}

// MarshalJSON makes UnitBytes implement json.Marshaler
func (u UnitBytes) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf(`"%d"`, u)), nil
}

func (u *UnitBytes) DecodeMapstructure(value interface{}) error {
	//将1M,1024类型的数据统一转换为字节类型
	v, err := units.FromHumanSize(fmt.Sprint(value))
	if err != nil {
		return err
	}
	*u = UnitBytes(v)

	//判断上面生成的字节数据是否是由二进制产生的
	if *u%1024 == 0{
		//由于会有二进制产生的数据，需要统一转换为十进制的字节数据
		//	t1 := units.BytesSize(float64(UnitBytes(*u))) //将二进制字节数536870912 转为为512MiB
		//由于历史原因 包部署为二进制，资源计算为十进制模式，会造成UI显示不一致的问题，在此统一转换为GiB的模式
		t1 := fmt.Sprintf("%.4g%s", float64(UnitBytes(*u))/1024/1024/1024, "GiB")
		t2, err := units.FromHumanSize(t1) //将512MiB进行十进制转换字节数512000000
		if err != nil {
			return err
		}
		*u = UnitBytes(t2)
	}
	return nil
}

